package java_option.player.javafx;

import java_option.Config;
import org.bytedeco.javacv.FFmpegFrameGrabber;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 程序启动类
 * 
 * @author java红了 <br/>
 *         2020-9-2716:13:41
 */
public class MainApplication extends Application {
	private static final Logger logger  = LoggerFactory.getLogger(MainApplication.class);

	public static Stage primaryStage;

	@Override
	public void start(Stage primaryStage) {

//		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
//			@Override
//			public void uncaughtException(Thread t, Throwable e) {
//				logger.debug("这里是全局异常处理 ====> " + t.getId() + "==> " + e.getLocalizedMessage());
//			}
//		});

		MainApplication.primaryStage = primaryStage;

		// 设置窗口属性
		primaryStage.setAlwaysOnTop(true); // 前端置顶显示
		primaryStage.setResizable(false); // 禁止改变窗口大小

//		primaryStage.setWidth(Config.DEFAULT_WIDTH);
//		primaryStage.setHeight(Config.Default_HEIGHT);
//		primaryStage.initStyle(StageStyle.UTILITY);// 不显示最大化 最小化按钮
		// 去掉窗口修饰,有两种方式
//		primaryStage.initStyle(StageStyle.TRANSPARENT);// 同时让弹出窗口透明
//		primaryStage.initStyle(StageStyle.UNDECORATED);

		try {
			Parent root = FXMLLoader.load(getClass().getResource("/Main.fxml"));
			Scene scene = new Scene(root);
			primaryStage.setScene(scene);
			primaryStage.show();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 界面加载完成以后 初始化FFmpegFrameGrabber
		new Thread(new Task<Void>() {
			@Override
			protected Void call() throws Exception {
				try {
					FFmpegFrameGrabber.tryLoad();
				} catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		}).start();

		final double oldX = primaryStage.getX();
		final double oldY = primaryStage.getY();
		double width = primaryStage.getWidth();
		double height = primaryStage.getHeight();

//		logger.debug(oldX + "," + oldY + " " + width + "," + height);
		// 监听窗口--不让窗口移动
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {

					// 一秒钟监听10次
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					double newX = primaryStage.getX();
					double newY = primaryStage.getY();
//					logger.debug("x=>{} y=>{}",newX,newY);
					//去除窗口定位限制
//					if (newX - oldX >= 1 || newY - oldY >= 1) {
//						primaryStage.setX(oldX);
//						primaryStage.setY(oldY);
//					}
				}
			}
		}).start();

	}

	/**
	 * 关闭窗口
	 */
	@Override
	public void stop() throws Exception {
		Platform.exit();// ? 后台还运行
		System.exit(0);
	}

	public static void main(String[] args) {
		launch(args);
	}
}
